const logger = require('winston')

/**
 * Handles error by printing to console in development env and builds and sends an error response
 * @param {Object} res - response object
 * @param {Object} err - error object
 */
const handleError = (res = {}, err = {}) => {
  // Prints error in console
  /*
  if (process.env.NODE_ENV === 'development') {
    console.log("log err:", err)
  }
  */

  let msg1 = "code: " + err.code + ", message: " 
        + JSON.stringify(err.message, null, 2)
  let msg2 = "stack: " + err.stack

  if (err.code >= 500) {
    logger.error(msg1)
    logger.error(msg2)
  } else {
    logger.warn(msg1)
    logger.warn(msg2)
  }

  // Sends error to user
  res.status(err.code).json({
    errors: {
      msg: err.message
    }
  })
}

module.exports = { handleError }
